var DOMUtils = {};

var _posMap = {
    1: 'beforeBegin',
    2: 'afterBegin',
    3: 'beforeEnd',
    4: 'afterEnd'
};
DOMUtils.insertHTML = function (html, rel, pos){
    if (rel.insertAdjacentHTML && !Utils.isOpera) {
        rel.insertAdjacentHTML(_posMap[pos], html);
        return;
    }
    var range = rel.ownerDocument.createRange();
    if (pos == 1 || pos == 3) {
        range.selectNodeContents(rel);
        range.collapse(pos == 1);
    } else {
        if (pos == 1) {
            range.setStartBefore(rel);
            range.collapse(true);
        } else {
            range.setEndAfter(rel);
            range.collapse(false);
        }
    }
    range.insertNode(range.createContextualFragment(html));
};

DOMUtils.fromHTML = function (html, rel, pos){
    var div = (!rel ? document :
        rel.ownerDocument || rel).createElement('div');
    div.innerHTML = html;
    var elm = div.firstChild;
    pos = pos | 0;
    if (pos == 1) {
        rel.parentNode.insertBefore(elm, rel);
    } else if (pos == 2) {
        rel.insertBefore(elm, rel.firstChild);
    } else if (pos == 3) {
        rel.appendChild(elm);
    } else if (pos == 4) {
        rel.parentNode.insertBefore(elm, rel.nextSibling);
    }
    return elm;
};

DOMUtils.addListener = function (obj, type, listener){
    if (obj.addEventListener) {
        obj.addEventListener(type, listener, false);
    } else {
        obj.attachEvent('on' + type, listener);
    }
};

DOMUtils.removeListener = function (obj, type, listener){
    if (obj.removeEventListener) {
        obj.removeEventListener(type, listener, false);
    } else {
        obj.detachEvent('on' + type, listener);
    }
};

DOMUtils.preventDefault = function (evt){
    if (evt.preventDefault) {
        evt.preventDefault();
    } else {
        evt.returnValue = false;
    }
};

DOMUtils.setText = function (elm, text){
    if ('textContent' in elm) {
        elm.textContent = text;
    } else {
        elm.innerText = text;
    }
};

DOMUtils.getWindow = function (elm){
    var doc = elm.ownerDocument || elm;
    return doc.defaultView || doc.parentWindow;
};

DOMUtils.getScrollBarWidth = function (doc){
    var div = DOMUtils.fromHTML('<div style="position:absolute;left:-32768px;top:0;width:200px;height:200px;overflow:scroll;"></div>',
        doc.body || doc.documentElement, 3);
    var width = div.offsetWidth - div.clientWidth;
    DOMUtils.removeNode(div);
    return width;
};

DOMUtils.removeNode = function (node){
    node.parentNode.removeChild(node);
};